package com.teacherprofile.manage.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacherprofile.common.constant.BusinessConstants;
import com.teacherprofile.common.constant.PatentsConstants;
import com.teacherprofile.common.constant.SoftwareCopyrightConstants;
import com.teacherprofile.common.core.domain.entity.SysUser;
import com.teacherprofile.common.enums.CheckStatus;
import com.teacherprofile.common.exception.ServiceException;
import com.teacherprofile.common.utils.DateUtils;
import com.teacherprofile.common.utils.SecurityUtils;
import com.teacherprofile.framework.manager.AsyncManager;
import com.teacherprofile.framework.manager.factory.AsyncFactory;
import com.teacherprofile.manage.domain.dto.CopyrightExportDTO;
import com.teacherprofile.manage.domain.dto.PatentsExportDTO;
import com.teacherprofile.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.teacherprofile.manage.mapper.PatentsMapper;
import com.teacherprofile.common.domain.Patents;
import com.teacherprofile.manage.service.IPatentsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 专利Service业务层处理
 *
 * @author qvtu
 * @date 2025-05-07
 */
@Service
public class PatentsServiceImpl extends ServiceImpl<PatentsMapper, Patents> implements IPatentsService {
    @Autowired
    private PatentsMapper patentsMapper;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询专利
     *
     * @param id 专利主键
     * @return 专利
     */
    @Override
    public Patents selectPatentsById(Long id) {
        return patentsMapper.selectPatentsById(id);
    }

    /**
     * 查询专利列表
     *
     * @param patents 专利
     * @return 专利
     */
    @Override
    public List<Patents> selectPatentsList(Patents patents) {
        return patentsMapper.selectPatentsList(patents);
    }

    /**
     * 新增专利
     *
     * @param patents 专利
     * @return 结果
     */
    @Override
    public int insertPatents(Patents patents) {
        String userName = patents.getUserName();
        if (ObjectUtils.isEmpty(userName)) {
            throw new RuntimeException("教职工号不能为空");
        }
        // 根据教职工号查询用户
        SysUser sysUser = userService.selectUserByUserName(userName);
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new RuntimeException("教职工号不存在");
        }
        // 用户存在，设置用户的userId、部门id和创建时间，然后保存
        patents.setUserId(sysUser.getUserId());
        patents.setDeptId(sysUser.getDeptId());
        patents.setCreateTime(DateUtils.getNowDate());
        return patentsMapper.insertPatents(patents);
    }

    /**
     * 修改专利
     *
     * @param patents 专利
     * @return 结果
     */
    @Override
    public int updatePatents(Patents patents) {
        patents.setUpdateTime(DateUtils.getNowDate());
        return patentsMapper.updatePatents(patents);
    }

    /**
     * 批量删除专利
     *
     * @param ids 需要删除的专利主键
     * @return 结果
     */
    @Override
    public int deletePatentsByIds(Long[] ids) {
        return patentsMapper.deletePatentsByIds(ids);
    }

    /**
     * 删除专利信息
     *
     * @param id 专利主键
     * @return 结果
     */
    @Override
    public int deletePatentsById(Long id) {
        return patentsMapper.deletePatentsById(id);
    }

    /**
     * 审批
     *
     * @param patents
     * @return
     */
    @Override
    public boolean check(Patents patents) {
        if (ObjectUtils.isNull(patents)) { // 非法参数
            throw new ServiceException(BusinessConstants.BUSINESS_ERROR);
        }
        if (patents.getCheckStatus().equals(CheckStatus.PASS.getCode())) {
            // 审核通过
            // 通知用户，审核通过
            AsyncManager.me().execute(AsyncFactory.sendPassMsgToOne(patents.getUserName(), PatentsConstants.CHECKED_PASS));
        } else {
            // 审核不通过
            // 通知用户，审核不通过
            AsyncManager.me().execute(AsyncFactory.sendRejectMsgToOne(patents.getUserName(), PatentsConstants.CHECKED_REJECT));

        }
        // 删除此条数据
//        System.out.println("审核");
//        System.out.println(patents);
        return updateById(patents);
    }

    /**
     * 导入专利
     *
     * @param patentsList
     * @return
     */
    @Transactional
    @Override
    public String importData(List<Patents> patentsList) {
        if (patentsList.isEmpty()) {
            throw new ServiceException("导入的数据不能为空！");
        }

        // 根据教职工号去重
        Set<String> patensSet = patentsList.stream().map(Patents::getUserName).collect(Collectors.toSet());

        // 根据教职工号查询对应的用户
        List<SysUser> userList = userService.selectUserByUserNames(patensSet);
        if (ObjectUtils.isEmpty(userList)) {
            throw new ServiceException("导入数据中教职工号不存在");
        }

        // 将用户列表转成Map，key为教职工号，value为SysUser对象
        Map<String, SysUser> userMap = userList.stream()
                .collect(Collectors.toMap(SysUser::getUserName, item -> item));
        for (Patents patents : patentsList) {
            SysUser sysUser = userMap.get(patents.getUserName());
            patents.setUserId(sysUser.getUserId());
            patents.setDeptId(sysUser.getDeptId());
        }
        return saveBatch(patentsList) ? "导入成功" : "导入失败";
    }
}
